<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/3/8
 * Time: 11:45
 */

namespace app\restful\controller;
use app\restful\code\ErrorCode;
use app\restful\model\Member as MemberModel;
use think\Exception;

// 用户注册，登录
class Member
{
    /**
     * 用户登录
     * @param $username
     * @param $pwd
     * @return false|\PDOStatement|string|\think\Collection
     * @throws Exception
     */
    public function login($username,$pwd)
    {
        if(empty($username)){
            throw new Exception('用户名不能为空',ErrorCode::USERNAME_CANNOT_EMPTY);
        }
        if(empty($pwd)){
            throw new Exception('密码不能为空',ErrorCode::USERNAME_CANNOT_EMPTY);
        }
        $pwd = $this->_md5($pwd);
        $where = [
            'username'=>$username,
            'pwd'     =>$pwd
        ];

        //dump($where);

        $res =  db("restful_member")->field("*")->where($where)->find();

       // dump($res);
        if(!$res){
            throw new Exception("用户名或密码错误",ErrorCode::USERNAME_OR_PWD_ERROR);
        }
        return $res['Id'];
    }

    /**
     * 用户注册
     * @param $username
     * @param $pwd
     * @return $this
     * @throws Exception
     */
    public function register($username,$pwd)
    {
        if(empty($username)){
            throw new Exception('用户名不能为空',ErrorCode::USERNAME_CANNOT_EMPTY);
        }
        if(empty($pwd)){
            throw new Exception('密码不能为空',ErrorCode::USERNAME_CANNOT_EMPTY);
        }
        if($this->_isUsernameExists($username)){
            throw new Exception('用户名已存在',ErrorCode::USERNAME_EXISTS);
        };
        $pwd = $this->_md5($pwd);
        $data = ['username'=>$username,'pwd'=>$pwd];

        return  MemberModel::create($data);
    }

    /**
     * 验证用户名是否存在
     * @param $username
     * @return bool
     */
    protected function _isUsernameExists($username)
    {
        $memberModel = new MemberModel();

        $res = $memberModel->db()->where('username',$username)->select();
        if($res){
            return true;
        }else{
            return false;
        }
    }

    /**
     * md5加密
     * @param $string
     * @param string $key
     * @return string
     */
    protected  function _md5($string,$key='mogen'){
        return md5($string.$key);
    }
}